﻿using Microsoft.Extensions.DependencyInjection;
using Simple.Services.System.Jobs;

public class TaskManagerService
{
    private static bool _isRunning = false;
    private static Func<Task> _taskAction;
    private Task _timer;
    private static readonly object _lock = new object();

    public TaskManagerService()
    {
    }

    public void Initialize(Func<Task> action)
    {
        _taskAction = action;
    }

    public void Start()
    {
        if (_taskAction == null)
        {
            throw new InvalidOperationException("TaskManagerService is not initialized.");
        }

        lock (_lock)
        {
            if (_isRunning)
            {
                return;
            }

            _isRunning = true;

            if (_timer == null || _timer.IsCompleted)
            {
                _timer = Task.Run(async () => await RunTask());
            }
        }
    }

    public void Stop()
    {
        lock (_lock)
        {
            _isRunning = false;
        }

        _timer?.Wait();
        _timer?.Dispose();
        _timer = null;
    }

    private async Task RunTask()
    {
        while (_isRunning)
        {
            // 计算到下一次执行的时间间隔
            var now = DateTime.Now;
            var nextRunTime = now.Date.AddDays(1).AddHours(2); // 明天的凌晨 2 点
            if (now.Hour < 2) // 如果当前时间在凌晨 2 点之前
            {
                nextRunTime = now.Date.AddHours(2); // 今天的凌晨 2 点
            }

            var delay = nextRunTime - now;
            Console.WriteLine($"Next execution scheduled at: {nextRunTime}");
            await Task.Delay(delay);

            if (_isRunning) // 确保服务仍在运行
            {
                try
                {
                    await _taskAction();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Task execution failed: {ex.Message}");
                }
            }
        }
    }
}

